package com.hsteach.service.myopia;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.PageUtils;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.dao.domain.myopia.MyopiaMission;
import com.hsteach.dao.domain.myopia.MyopiaSchoolMission;
import com.hsteach.dao.mapper.MyopiaInfoMapper;
import com.hsteach.dao.mapper.MyopiaMapper;
import com.hsteach.dao.mapper.MyopiaMissionMapper;
import com.hsteach.enums.BooleanEnum;
import com.hsteach.framework.feign.client.xgk.dto.ret.AreaSchoolRet;
import com.hsteach.framework.web.service.AuthService;
import com.hsteach.web.controller.myopia.dto.MissionListDTO;
import com.hsteach.web.controller.myopia.dto.MyopiaMissionInfoDTO;
import com.hsteach.web.controller.myopia.vo.MyopiaSchoolMissionVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 视管理任务Service业务层处理
 *
 * @author lx
 * @date 2023-07-07
 */
@Service
public class MyopiaMissionService extends ServiceImpl<MyopiaMissionMapper, MyopiaMission> {

    @Autowired
    private MyopiaMapper myopiaMapper;

    @Autowired
    private MyopiaInfoMapper infoMapper;

    @Autowired
    private MyopiaSchoolMissionService schoolMissionService;

    @Autowired
    private MyopiaMissionMapper myopiaMissionMapper;

    @Autowired
    private AuthService authService;

    /**
     * 新增近视管理任务
     *
     * @param mission
     * @return
     */
    @Transactional
    public void add(MyopiaMission mission) {
        if (mission.getEndTime().compareTo(new Date()) <= 0) {
            throw new ServiceException("结束时间必须大于当前时间");
        }
        if (mission.getName().length() > 25) {
            throw new ServiceException("任务名称限定为25字以内");
        }
        //判断是否重名
        int count = count(new LambdaQueryWrapper<MyopiaMission>()
                .eq(MyopiaMission::getName, mission.getName())
                .eq(MyopiaMission::getDelFlag,0));
        if (count > 0){
            throw new ServiceException("任务名称重复");
        }

        createMission(mission);
    }

    public void createMission(MyopiaMission mission) {
        List<AreaSchoolRet> schools = authService.getSchool("area");
        //获取总人数
        mission.setStuCount(0);
        mission.setStatus(0);
        mission.setUpCount(0);
        //获取区域学校总数
        mission.setNupCount(schools.size());
        mission.setSchCount(schools.size());
        save(mission);
        //初始化当前任务涉及到的学校
        List<MyopiaSchoolMission> schoolMissions = schools.stream().map(e -> {
            MyopiaSchoolMission schoolMission = new MyopiaSchoolMission();
            schoolMission.setMissionId(mission.getId());
            schoolMission.setSchoolId(e.getId());
            schoolMission.setSchoolName(e.getName());
            return schoolMission;
        }).collect(Collectors.toList());
        schoolMissionService.saveBatch(schoolMissions);
    }

    /**
     * 获取近视管理任务列表
     */
    public List<MyopiaMission> getList(MissionListDTO dto) {
        return list(new LambdaQueryWrapper<MyopiaMission>()
                .like(StringUtils.isNotEmpty(dto.getName()), MyopiaMission::getName, dto.getName())
                .eq(MyopiaMission::getDelFlag, 0)
                .orderByDesc(MyopiaMission::getId));
    }


    /**
     * 获取近视管理任务详情
     *
     * @param dto
     * @return
     */
    public List<MyopiaSchoolMission> getInfo(MyopiaMissionInfoDTO dto) {
        MyopiaMission mission = getOne(new LambdaQueryWrapper<MyopiaMission>().eq(MyopiaMission::getId, dto.getMissionId())
                .eq(MyopiaMission::getDelFlag, 0));
        if (ObjectUtils.isEmpty(mission)) {
            throw new ServiceException("任务不存在或已删除");
        }
        PageUtils.startPage(dto.getPageNum(), dto.getPageSize());
        List<MyopiaSchoolMission> schoolMissionList;
        if (dto.getStatus().equals(BooleanEnum.FALSE.getCode())) {
            schoolMissionList = schoolMissionService.list(new LambdaQueryWrapper<MyopiaSchoolMission>()
                    .eq(MyopiaSchoolMission::getMissionId, dto.getMissionId())
                    .like(dto.getSchoolName() != null, MyopiaSchoolMission::getSchoolName, dto.getSchoolName())
                    .and(lambdaQueryWrapper -> lambdaQueryWrapper
                            .eq(MyopiaSchoolMission::getRiskStatus, dto.getStatus())
                            .or().eq(MyopiaSchoolMission::getCensusStatus, dto.getStatus()))
            );
        } else {
            schoolMissionList = schoolMissionService.list(new LambdaQueryWrapper<MyopiaSchoolMission>()
                    .eq(MyopiaSchoolMission::getMissionId, dto.getMissionId())
                    .like(dto.getSchoolName() != null, MyopiaSchoolMission::getSchoolName, dto.getSchoolName())
                    .eq(MyopiaSchoolMission::getRiskStatus, dto.getStatus())
                    .eq(MyopiaSchoolMission::getCensusStatus, dto.getStatus()));
        }

        return schoolMissionList;
    }

    /**
     * 批量删除任务
     *
     * @param ids
     */
    @Transactional
    public void batchDel(Long[] ids) {
        //批量删除任务
        List<Long> idList = Arrays.asList(ids);
        myopiaMissionMapper.delByIds(idList);
        //删除学校完成情况
        schoolMissionService.remove(new LambdaQueryWrapper<MyopiaSchoolMission>()
                .in(MyopiaSchoolMission::getMissionId, idList));
    }

    /**
     * 获取最新一次非区域上传的任务
     *
     * @return
     */
    public MyopiaMission getNewMission() {
        return getOne(new LambdaQueryWrapper<MyopiaMission>().select(MyopiaMission::getId)
                .eq(MyopiaMission::getDelFlag, BooleanEnum.FALSE)
                .eq(MyopiaMission::getAreaUp,0)
                .orderByDesc(MyopiaMission::getId)
                .last("LIMIT 1;"));

    }

    public List<MyopiaSchoolMissionVO> schoolList(MissionListDTO dto) {
        if (dto.getSchoolId() == null){
            throw new ServiceException("参数异常");
        }
        dto.setSchoolId(SecurityUtils.getAuthInfo().getOrganizeId());
        return myopiaMissionMapper.schoolList(dto);
    }
}
